package com.bluesky.example.myclassloader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * load classes from a specified folder
 * @author Administrator
 *
 */
public class MyClassLoader extends ClassLoader {

	private String baseDir;

	public MyClassLoader(String baseDir) {
		this.baseDir = baseDir;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {

		try {
			Class<?> cls = super.findClass(name);
			return cls;
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
		}

		// find it in the baseDir
		/**
		 * name : com.abc.proj.clazz
		 */
		String filePathName = baseDir + name.replaceAll("\\.", "\\\\")+".class";
		try {
			InputStream is = new FileInputStream(filePathName);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buff = new byte[100];
			while (true) {
				int len;

				len = is.read(buff);

				if (len > 0)
					baos.write(buff, 0, len);
				else
					break;

			}

			return defineClass(name, baos.toByteArray(), 0, baos.size());

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		throw new ClassNotFoundException();

	}

	public static void main(String[] args) {
		ClassLoader myClassLoader = new MyClassLoader(
				"E:\\studio\\java\\eclipse-ganymede\\TestClassLoader\\bin\\");
		try {
			Class cls = myClassLoader.loadClass("com.abc.classloader.Foo");

			Object o;
			try {
				o = cls.newInstance();
				System.out.println(o);
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
